// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <gtest/gtest.h>
#include <climits>
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <cantor/parser/parser.h>
#include <cantor/utility/json_reader.h>
#include <tests/config.h>
#include <tests/paser/node_check.h>


int main(int argc, char *argv[]) {
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

namespace cantor::parser {
    class DataJson {
    public:
        static DataJson &instance() {
            static DataJson instance;
            return instance;
        }

        const nlohmann::ordered_json &json() const { return json_; }

    private:
        DataJson() {
            std::string json_path = turbo::str_cat(testing::test_root, "/data/create_type.json");
            auto rs = read_file(json_path);
            KCHECK(rs.ok());
            json_ = std::move(rs).value_or_die();
        }

        nlohmann::ordered_json json_;
    };

    void test_case(const std::string & type, bool show_json = false) {
        auto &json = DataJson::instance().json();
        auto list = json[type].get<std::vector<nlohmann::ordered_json>>();
        for (auto &item : list) {
            std::string sql = item["sql"].get<std::string>();
            auto result = item["result"].get<nlohmann::ordered_json>();
            KLOG(INFO)<<NOPREFIX<<"testing sql: "<<sql;
            cantor::parser::SqlParser parser;
            parser.parse(sql);
            ASSERT_EQ(parser.error, cantor::parser::SUCCESS)<<parser.syntax_err_str;
            ASSERT_EQ(1, parser.result.size());

            auto *stmt = (CreateTypeStmt *) parser.result[0];

            auto pj = stmt->to_json();
            if (show_json) {
                std::cout << pj << std::endl;
            }
            if (!result.empty()) {
                ASSERT_EQ(result, pj);
                KLOG(INFO)<<NOPREFIX<<"compare stand json ast ...";
            }

            KLOG(INFO)<<NOPREFIX<<"testing done ..............";
        }

    }
    TEST(test_parser, base_case) {
        test_case("base_case", true);
    }
}  // namepace cantor::parser